package com.iut.quizz;

import com.iut.contactlist.*;
import com.iut.message.*;
import com.iut.sms.*;
import com.iut.base_de_donnees.*;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.util.SparseArray;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

public class App extends Activity implements OnClickListener {

	private TextView question = null;
	private RadioGroup reponses = null;
	private RadioButton reponse1, reponse2, reponse3, reponse4,
			reponseUser = null;
	private Button butSend = null;
	private int numQuestion = 0;
	private static int totalContact;
	private static int totalQuestion;
	private static int totalMessages;
	private ContactList contactList;
	private MessageList messageList;
	private SendSMS smsSender;
	public QuestRepBDD db = new QuestRepBDD(this);
	private SparseArray <QuestRep> listQuest;

	/**
	 * When App is created
	 * 
	 * @param savedInstanceState
	 *            States of the app
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.game);

		this.initGame();
		this.initContacts();
		this.initQuestions();
		this.initMessages();
		this.initSMSSender();
	}

	/**
	 * Event when user Click of the send Button
	 * 
	 * @param arg0
	 *            The view of the App
	 */
	@Override
	public void onClick(View arg0) {
		try {
			
			Log.i("VALIDATE QUESTION", "Validate question");
			
			// Get response from user
			this.setReponseUser((RadioButton) findViewById(this.getReponses()
					.getCheckedRadioButtonId()));

			// Check answer
			this.checkAnswer(this.getReponseUser());
			
			//TODO: Move that
			if (this.getNumQuestion() < App.totalQuestion) {
				this.nextQuestion();
			} else {
				this.endGame();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	/**
	 * 
	 * @param Menu Menu of the app
	 * @return boolean
	 */
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	/**
	 * Init the base of game: DB, IHM
	 * 
	 */
	public void initGame() {
		//Init IHM
		this.setQuestion((TextView) findViewById(R.id.question));
		this.setReponses((RadioGroup) findViewById(R.id.radioGroupReponse));
		this.setReponse1((RadioButton) findViewById(R.id.Reponse1));
		this.setReponse2((RadioButton) findViewById(R.id.Reponse2));
		this.setReponse3((RadioButton) findViewById(R.id.Reponse3));
		this.setReponse4((RadioButton) findViewById(R.id.Reponse4));

		this.setButSend((Button) findViewById(R.id.ButEnvoi));
		
		//Init listener
		this.getButSend().setOnClickListener(this);
	}

	/**
	 * Initalisation of contacts Get from phone contact and print it
	 * 
	 */
	public void initContacts() {
		Log.i("INIT CONTACT", "Init contacts");
		try {
			this.setContactList(new ContactList(this));
			App.totalContact = this.getContactList().getContacts().size();
			Log.i("TOTAL CONTACTS", "Total contacts " + App.totalContact);
		} catch (ContactListException e) {
			Log.e("MainActivity::initContacts", e.getMessage());
		}
	}

	/**
	 * Initalisation question and answers Get from database and print it
	 * 
	 */
	private void initQuestions() {
		try {
			Log.i("INIT QUESTION", "Init questions");
			
			//Init questions in local database
			this.addQuestionInDb();
			this.recupQuestRep();

			// Get the number of questions
			App.totalQuestion = this.getListQuest().size();
			Log.i("TOTAL QUESTIONS", "Total questions " + App.totalQuestion);

			// Init the question number, we start to 0
			this.setNumQuestion(0);
			this.nextQuestion();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Initalisation messages to send when user loose
	 * 
	 */
	private void initMessages() {
		try {
			Log.i("INIT MESSAGES", "Init messages");
			this.messageList = new MessageList();

			// Get the number of questions
			App.totalMessages = this.getMessageList().getMessages().size();
			Log.i("TOTAL MESSAGES", "Total messages " + App.totalMessages);
		} catch (Exception e) {
			Log.e("ERROR MESSAGES", e.getMessage());
		}
	}
	
	/**
	 * Initalisation SMS Handler when an user loose
	 * 
	 */
	private void initSMSSender() {

		try {
			Log.i("INIT SMSSENDER", "Init SMSSender");
			this.smsSender = new SendSMS();
		} catch (Exception e) {
			Log.e("ERROR SMSSENDER", e.getMessage());
		}
	}
	
	/**
	 * Add questions in local database
	 * 
	 */
	private void addQuestionInDb() {
		/* Debut add des questions dans la BD */
		db.open();
		
		db.removeQuestRepAll();
		
		db.addQuestRep(new QuestRep("Qui est le meilleur prof du monde ?",
				"Benoit Diard", "Alexandre Benoit", "Les deux",
				"Maitre Yoda", 4));

		db.addQuestRep(new QuestRep("Quel est la réponse à la vie et à l'univers et le reste ?",
				"Quarante boeux", "Adriana Karembeux", "Quarante-deux",
				"Vous pouvez répéter la question ?", 3));

		db.addQuestRep(new QuestRep("Lorsqu'un pancake tombe dans la neige avant le 31 décembre, on dit qu'il est : ",
				"Tombé dans la neige avant le 31 décembre", "Une Kipa surgelé",
				"Un frizby comestible", "La réponse D", 2));

		db.addQuestRep(new QuestRep("A qui ira le pétrole de l'Irak ?",
				"Obi-Wan Kenobi", "Au peuple Irakien", "A la France",
				"Aux Etats-Unis", 1));

		db.addQuestRep(new QuestRep("Qu'est-ce qui est petit, carré et rouge ?",
				"Un cube de kub or", "un lego rouge", "un petit carré rouge",
				"un petit rubis", 3));

		db.addQuestRep(new QuestRep("Si la loutre est à la girafe ce que le castor est à l'éléphant, alors : ",
				"Superman a une bouille incroyable", "L'abeille coule",
				"Le mammouth écrase les prix",
				"Il ne faut pas chourrer le bien du voisin", 1));

		db.addQuestRep(new QuestRep("Quel est la meilleur réplique de Star Wars ?",
				"It's a crap !",
				"You were the shoes on one !",
				"Get in there, you big furry oaf! I don't care what you smell!",
				"I'm your Mother !", 4));

		db.addQuestRep(new QuestRep("Tu connais l'histoire du con qui répondait toujours non ?",
				"Oui", "Non", "heu...", "peut-être", 2));

		db.addQuestRep(new QuestRep("Quel est la congolexicomatisation des lois du marché ?",
				"Mais oui c'est clair", "La nucléarité des rollers",
				"La dynamite des sports",
				"C'est une kermesse inter-continentaliste", 1));

		db.addQuestRep(new QuestRep("Qui gagnera la bataille ?", "San-Goku",
				"SuperMan", "Link", "Luke Skywalker", 4));

		db.addQuestRep(new QuestRep("pierre, papier ou ciseaux ?", "Pierre",
				"Papier", "Ciseaux", "Puit (tricheur)", 4));

		db.addQuestRep(new QuestRep("Robot, Humain ou Alien ?", "Robot",
				"Humain", "Alien", "Un mix (dégueu...)", 4));

		db.addQuestRep(new QuestRep("Que contient la boite de pandore ?",
				"Question suivante !",
				"Un terrible secret",
				"Je sais pas je l'ai jamais ouverte",
				"Un petit gros roux diforme manchot unijambiste",
				1));

		db.addQuestRep(new QuestRep("Trouvez l'erreur : ", "Daft Punk",
				"L'erreur", "Justine Bieber", "David Guetta", 2));

		db.addQuestRep(new QuestRep("Qu'es qu'un sardinaliste ?",
				"Un mangeur de sardine", "Une sardine journaliste",
				"Un maquereau en moins bien",
				"Un singe sans bras jouant du djembé", 3));

		db.addQuestRep(new QuestRep("Qui regarde ses pieds ?",
				"La reine d'angletterre en VTT", "Un nain à grand pied",
				"Un cul-de-jatte en voiture", "Je passe", 1));

		db.addQuestRep(new QuestRep("Qui à dit : ...", "Jules Caesar",
				"Chuck Norris", "SIRI", "Obi-Wan Kenobi", 3));

		db.addQuestRep(new QuestRep("Brûle-tampon ou Ragniagnia ?",
				"Pêre Noël", "Castor", "Horatio", "Kamoulox", 4));

		db.addQuestRep(new QuestRep("Est-ce que tu es déjà arrivé à pied par la Chine ?", "Kawa ?",
				"Oui, mais c'est long", "Dégueu !",
				"Non ce n'est pas possible", 3));

		db.addQuestRep(new QuestRep("Quel est le pire pour Batman ?",
				"Devoir donner sa langue au chat", "Gagner un joker",
				"Ne pas avoir la main verte", "Devenir une armoire à glace", 1));
		
		db.addQuestRep(new QuestRep("Combien de développeurs ont développé cette appli ?",
				"1 (I'm the King of the World)", "2 (Car à 2 tout est mieux)",
				"3 (Un plan à 3 ça se refuse pas)",
				"4 (car plus on est, plus on jouit)", 3));
		db.close();
		/* Fin add des questions dans la BD */
	}
	
	public void recupQuestRep()
	{
		db.open();
		this.setListQuest(db.getAllQuest());
		db.close();
	}
	
	/**
	 * Check the answer of the user and apply punition
	 * 
	 * @param answer
	 * 			RadioButton of the answer selected by user
	 */
	public void checkAnswer(RadioButton answer) {
		try {
			
			Log.i("CHECK ANSWER", "Question num: " + this.getNumQuestion() );
			
			boolean valide = false;
			valide = this.validAnswer(answer);
			
			if (valide == false) {
				Contact c = this.contactList.getRandomContact();
				Message m = this.messageList.getRandomMessage();
				this.smsSender.sendSMS(c, m);
				GameOverScreen.numberSMS++;
				Log.i("FAUX EN FAIT ! Nombre de réponses fausses :", GameOverScreen.numberSMS+"");
			}
			
			
		} catch (Exception e) {
			Log.e("MainActivity::checkAnswer", e.getMessage());
		}
		
	}
	
	/**
	 * Check if the answer of the user is good or not
	 * 
	 * @param answer
	 *            RadioButton of the answer selected by user
	 * @return boolean The validation status
	 */
	public boolean validAnswer(RadioButton answer) {
		try {
			int goodResponse = this.getListQuest().get(this.getNumQuestion()).getGood_reponse();
			int valueSendResponse = 0;
			
			switch (answer.getId()) {
				case R.id.Reponse1:
					valueSendResponse = 1;
					break;
				case R.id.Reponse2:
					valueSendResponse = 2;
					break;
				case R.id.Reponse3:
					valueSendResponse = 3;
					break;
				case R.id.Reponse4:
					valueSendResponse = 4;
					break;
				default:
					throw new Exception("This answer is not supported yet");
			}
			
			//Test if response good
			if  (goodResponse == valueSendResponse) {
				return true;
			}
			
			Log.i("VALID ANSWER", "Good response: " + goodResponse + " User response: "+ valueSendResponse);
			
		} catch (Exception e) {
			Log.e("MainActivity::validAnswer", e.getMessage());
		}
		
		return false;
	}

	/**
	 * Get the next question of the Quizz and print it
	 */
	public void nextQuestion() {
		//Get the QuestRep object (that contains question + response)
		QuestRep currentQuestion = listQuest.get(this.getNumQuestion());
		
		// Get question and print it
		this.getQuestion().setText(currentQuestion.getQuestion());
		// increment question number
		this.setNumQuestion(this.getNumQuestion() + 1);
		
		//Get responses and print it
		this.getReponse1().setText(currentQuestion.getReponse_1());
		this.getReponse2().setText(currentQuestion.getReponse_2());
		this.getReponse3().setText(currentQuestion.getReponse_3());
		this.getReponse4().setText(currentQuestion.getReponse_4());
		
		this.getReponse1().setChecked(true);
		
		Log.i("NEXT QUESTION", "Number " + this.numQuestion);
	}

	/**
	 * Lauch the end of the Game
	 */
	public void endGame() {
		// TODO Free the RAM
		Intent i = new Intent(this,GameOverScreen.class);
		startActivity(i);
		Log.i("END GAME", "END GAME");
	}

	/**
	 * @return the question
	 */
	public TextView getQuestion() {
		return question;
	}

	/**
	 * @param question the question to set
	 */
	public void setQuestion(TextView question) {
		this.question = question;
	}

	/**
	 * @return the reponses
	 */
	public RadioGroup getReponses() {
		return reponses;
	}

	/**
	 * @param reponses the reponses to set
	 */
	public void setReponses(RadioGroup reponses) {
		this.reponses = reponses;
	}

	/**
	 * @return the reponse1
	 */
	public RadioButton getReponse1() {
		return reponse1;
	}

	/**
	 * @param reponse1 the reponse1 to set
	 */
	public void setReponse1(RadioButton reponse1) {
		this.reponse1 = reponse1;
	}

	/**
	 * @return the reponse2
	 */
	public RadioButton getReponse2() {
		return reponse2;
	}

	/**
	 * @param reponse2 the reponse2 to set
	 */
	public void setReponse2(RadioButton reponse2) {
		this.reponse2 = reponse2;
	}

	/**
	 * @return the reponse3
	 */
	public RadioButton getReponse3() {
		return reponse3;
	}

	/**
	 * @param reponse3 the reponse3 to set
	 */
	public void setReponse3(RadioButton reponse3) {
		this.reponse3 = reponse3;
	}

	/**
	 * @return the reponse4
	 */
	public RadioButton getReponse4() {
		return reponse4;
	}

	/**
	 * @param reponse4 the reponse4 to set
	 */
	public void setReponse4(RadioButton reponse4) {
		this.reponse4 = reponse4;
	}

	/**
	 * @return the reponseUser
	 */
	public RadioButton getReponseUser() {
		return reponseUser;
	}

	/**
	 * @param reponseUser the reponseUser to set
	 */
	public void setReponseUser(RadioButton reponseUser) {
		this.reponseUser = reponseUser;
	}

	/**
	 * @return the butSend
	 */
	public Button getButSend() {
		return butSend;
	}

	/**
	 * @param butSend the butSend to set
	 */
	public void setButSend(Button butSend) {
		this.butSend = butSend;
	}

	/**
	 * @return the numQuestion
	 */
	public int getNumQuestion() {
		return numQuestion;
	}

	/**
	 * @param numQuestion the numQuestion to set
	 */
	public void setNumQuestion(int numQuestion) {
		this.numQuestion = numQuestion;
	}

	/**
	 * @return the totalContact
	 */
	public static int getTotalContact() {
		return totalContact;
	}

	/**
	 * @param totalContact the totalContact to set
	 */
	public static void setTotalContact(int totalContact) {
		App.totalContact = totalContact;
	}

	/**
	 * @return the totalQuestion
	 */
	public static int getTotalQuestion() {
		return totalQuestion;
	}

	/**
	 * @param totalQuestion the totalQuestion to set
	 */
	public static void setTotalQuestion(int totalQuestion) {
		App.totalQuestion = totalQuestion;
	}

	/**
	 * @return the totalMessages
	 */
	public static int getTotalMessages() {
		return totalMessages;
	}

	/**
	 * @param totalMessages the totalMessages to set
	 */
	public static void setTotalMessages(int totalMessages) {
		App.totalMessages = totalMessages;
	}

	/**
	 * @return the contactList
	 */
	public ContactList getContactList() {
		return contactList;
	}

	/**
	 * @param contactList the contactList to set
	 */
	public void setContactList(ContactList contactList) {
		this.contactList = contactList;
	}

	/**
	 * @return the messageList
	 */
	public MessageList getMessageList() {
		return messageList;
	}

	/**
	 * @param messageList the messageList to set
	 */
	public void setMessageList(MessageList messageList) {
		this.messageList = messageList;
	}

	/**
	 * @return the smsSender
	 */
	public SendSMS getSmsSender() {
		return smsSender;
	}

	/**
	 * @param smsSender the smsSender to set
	 */
	public void setSmsSender(SendSMS smsSender) {
		this.smsSender = smsSender;
	}

	public SparseArray<QuestRep> getListQuest() {
		return listQuest;
	}

	public void setListQuest(SparseArray<QuestRep> listQuest) {
		this.listQuest = listQuest;
	}

}
